import React, { useState, useEffect, useMemo } from 'react';
import { Layout, Menu, Breadcrumb, Card, Row, Col, Statistic, Typography, Spin, message, Button, Space, Alert, Tooltip, Progress, List, Avatar, Divider, notification, Badge } from 'antd';
import {
  UserOutlined,
  FileOutlined,
  DashboardOutlined,
  MessageOutlined,
  TeamOutlined,
  BarChartOutlined,
  SettingOutlined,
  LogoutOutlined,
  WhatsAppOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  DisconnectOutlined
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation, useMatch } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import api from '../../services/api';
import socketService from '../../services/socket';

const { Header, Content, Footer, Sider } = Layout;
const { Title, Text } = Typography;
const { SubMenu } = Menu;

// 使用React.memo包装AdminDashboard组件，减少不必要的重渲染
const AdminDashboard = React.memo(() => {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { logout, user } = useAuth();
  const pathSnippets = location.pathname.split('/').filter(i => i);
  
  // 添加渲染跟踪
  console.log(`AdminDashboard渲染，路径: ${location.pathname}`, new Date().toISOString());

  const onCollapse = (collapsed) => {
    setCollapsed(collapsed);
  };

  const handleMenuClick = (e) => {
    if (location.pathname !== e.key) {
      navigate(e.key);
    }
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  // 使用useMemo缓存面包屑数据，避免每次渲染都重新计算
  const breadcrumbNameMap = useMemo(() => {
    return {
      '/admin': '管理中心',
      '/admin/users': '用户管理',
      '/admin/preset-files': '预设文件管理',
      '/admin/activity-report': '活跃度报告',
      '/admin/settings': '系统设置',
    };
  }, []);

  // 使用useMemo缓存面包屑items
  const breadcrumbItems = useMemo(() => {
    return [
      { title: '首页', key: 'home' },
      ...pathSnippets.map((_, index) => {
        const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
        return {
          title: breadcrumbNameMap[url],
          key: url
        };
      })
    ];
  }, [pathSnippets, breadcrumbNameMap]);

  // 使用useMemo缓存菜单项，避免重复创建
  const menuItems = useMemo(() => {
    return [
      {
        key: '/admin',
        icon: <DashboardOutlined />,
        label: '管理中心'
      },
      {
        key: '/admin/users',
        icon: <UserOutlined />,
        label: '用户管理'
      },
      {
        key: '/admin/preset-files',
        icon: <FileOutlined />,
        label: '预设文件管理'
      },
      {
        key: '/admin/activity-report',
        icon: <BarChartOutlined />,
        label: '活跃度报告'
      },
      {
        key: 'sub1',
        icon: <SettingOutlined />,
        label: '系统设置',
        children: [
          {
            key: '/admin/settings',
            label: '基本设置'
          },
          {
            key: '/admin/settings/sensitive',
            label: '敏感内容设置'
          },
          {
            key: '/admin/settings/blacklist',
            label: '黑名单管理'
          }
        ]
      },
      {
        key: 'logout',
        icon: <LogoutOutlined />,
        danger: true,
        label: '退出登录',
        onClick: handleLogout
      }
    ];
  }, [handleLogout]);

  // 检查当前路径
  const isHome = useMatch('/admin') && 
    !pathSnippets.includes('users') && 
    !pathSnippets.includes('preset-files') && 
    !pathSnippets.includes('activity-report') && 
    !pathSnippets.includes('settings');

  const [loading, setLoading] = useState(false);
  const [dashboardData, setDashboardData] = useState({
    totalUsers: 0,
    connectedUsers: 0,
    totalMessages: 0,
    todayMessages: 0
  });
  const [userConnections, setUserConnections] = useState([]);
  const [recentActivities, setRecentActivities] = useState([]);
  const [systemAlerts, setSystemAlerts] = useState([]);

  // 获取仪表板数据
  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      
      // 获取统计数据
      const statsResponse = await api.get('/admin/dashboard/stats');
      setDashboardData(statsResponse.data);
      
      // 获取用户连接状态
      const connectionsResponse = await api.get('/admin/whatsapp/connections');
      setUserConnections(connectionsResponse.data);
      
      // 获取最近活动
      const activitiesResponse = await api.get('/admin/activities/recent');
      setRecentActivities(activitiesResponse.data);
      
    } catch (error) {
      console.error('获取仪表板数据失败:', error);
      notification.error({
        message: '数据加载失败',
        description: '无法获取仪表板数据，请稍后重试'
      });
    } finally {
      setLoading(false);
    }
  };

  // 监听实时状态更新
  useEffect(() => {
    // 监听用户状态变化
    const handleUserStatusChange = (data) => {
      console.log('用户状态变化:', data);
      
      // 更新用户连接列表
      setUserConnections(prev => 
        prev.map(conn => 
          conn.userId === data.userId 
            ? { ...conn, status: data.status, lastUpdate: new Date() }
            : conn
        )
      );
      
      // 显示通知
      if (data.type === 'success') {
        notification.success({
          message: 'WhatsApp连接状态',
          description: data.message,
          duration: 3
        });
      } else if (data.type === 'warning') {
        notification.warning({
          message: 'WhatsApp连接状态',
          description: data.message,
          duration: 5
        });
      }
    };

    // 监听敏感内容检测
    const handleSensitiveContent = (data) => {
      console.log('检测到敏感内容:', data);
      
      notification.warning({
        message: '敏感内容检测',
        description: `用户 ${data.contact.name} 发送了包含${data.contentType}的消息`,
        duration: 10
      });
      
      // 添加到系统警报
      setSystemAlerts(prev => [{
        id: Date.now(),
        type: 'sensitive_content',
        message: `检测到敏感内容: ${data.contentType}`,
        userId: data.userId,
        contactName: data.contact.name,
        timestamp: new Date()
      }, ...prev.slice(0, 9)]); // 保留最新10条
    };

    socketService.onEvent('admin:user_status_change', handleUserStatusChange);
    socketService.onEvent('sensitive:content', handleSensitiveContent);

    return () => {
      socketService.offEvent('admin:user_status_change');
      socketService.offEvent('sensitive:content');
    };
  }, []);

  // 组件加载时获取数据
  useEffect(() => {
    if (user && user.role === 'admin') {
      fetchDashboardData();
      
      // 设置定时刷新
      const interval = setInterval(fetchDashboardData, 30000); // 30秒刷新一次
      
      return () => clearInterval(interval);
    }
  }, [user]);

  // 强制断开用户连接
  const forceDisconnectUser = async (userId) => {
    try {
      await api.post(`/whatsapp/user/${userId}/disconnect`);
      notification.success({
        message: '操作成功',
        description: `已强制断开用户 ${userId} 的WhatsApp连接`
      });
      fetchDashboardData(); // 刷新数据
    } catch (error) {
      notification.error({
        message: '操作失败',
        description: '无法断开用户连接，请稍后重试'
      });
    }
  };

  // 用户连接状态表格列定义
  const connectionColumns = [
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      render: (text, record) => (
        <Space>
          <Avatar icon={<UserOutlined />} size="small" />
          <div>
            <div>{record.fullName || text}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {record.role === 'admin' ? '管理员' : '销售人员'}
            </Text>
          </div>
        </Space>
      )
    },
    {
      title: '连接状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusConfig = {
          connected: { color: 'success', icon: <CheckCircleOutlined />, text: '已连接' },
          connecting: { color: 'processing', icon: <SyncOutlined spin />, text: '连接中' },
          disconnected: { color: 'default', icon: <CloseCircleOutlined />, text: '未连接' },
          error: { color: 'error', icon: <ExclamationCircleOutlined />, text: '错误' }
        };
        
        const config = statusConfig[status] || statusConfig.disconnected;
        
        return (
          <Badge 
            status={config.color} 
            text={
              <Space>
                {config.icon}
                {config.text}
              </Space>
            } 
          />
        );
      }
    },
    {
      title: '手机号码',
      dataIndex: 'phoneNumber',
      key: 'phoneNumber',
      render: (phone) => phone || '-'
    },
    {
      title: '连接时间',
      dataIndex: 'connectedAt',
      key: 'connectedAt',
      render: (time) => time ? new Date(time).toLocaleString() : '-'
    },
    {
      title: '最后活动',
      dataIndex: 'lastActivity',
      key: 'lastActivity',
      render: (time) => time ? new Date(time).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          {record.status === 'connected' && (
            <Tooltip title="强制断开连接">
              <Button 
                type="text" 
                danger 
                icon={<DisconnectOutlined />}
                onClick={() => forceDisconnectUser(record.userId)}
              />
            </Tooltip>
          )}
        </Space>
      )
    }
  ];

  // 渲染统计卡片
  const renderStatCards = () => (
    <Row gutter={[16, 16]}>
      <Col xs={24} sm={12} md={6}>
        <Card>
          <Statistic
            title="总用户数"
            value={dashboardData.totalUsers}
            prefix={<UserOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col xs={24} sm={12} md={6}>
        <Card>
          <Statistic
            title="在线用户"
            value={dashboardData.connectedUsers}
            prefix={<WhatsAppOutlined />}
            valueStyle={{ color: '#52c41a' }}
            suffix={`/ ${dashboardData.totalUsers}`}
          />
          <Progress 
            percent={dashboardData.totalUsers > 0 ? 
              Math.round((dashboardData.connectedUsers / dashboardData.totalUsers) * 100) : 0
            }
            size="small"
            showInfo={false}
            style={{ marginTop: 8 }}
          />
        </Card>
      </Col>
      <Col xs={24} sm={12} md={6}>
        <Card>
          <Statistic
            title="总消息数"
            value={dashboardData.totalMessages}
            prefix={<MessageOutlined />}
            valueStyle={{ color: '#722ed1' }}
          />
        </Card>
      </Col>
      <Col xs={24} sm={12} md={6}>
        <Card>
          <Statistic
            title="今日消息"
            value={dashboardData.todayMessages}
            prefix={<MessageOutlined />}
            valueStyle={{ color: '#fa8c16' }}
          />
        </Card>
      </Col>
    </Row>
  );

  // 渲染系统警报
  const renderSystemAlerts = () => (
    <Card 
      title="系统警报" 
      size="small"
      extra={
        <Button 
          type="text" 
          icon={<ReloadOutlined />} 
          onClick={() => setSystemAlerts([])}
        >
          清空
        </Button>
      }
    >
      {systemAlerts.length === 0 ? (
        <Text type="secondary">暂无系统警报</Text>
      ) : (
        <List
          size="small"
          dataSource={systemAlerts}
          renderItem={(alert) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<ExclamationCircleOutlined />} size="small" />}
                title={alert.message}
                description={
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {alert.timestamp.toLocaleString()}
                  </Text>
                }
              />
            </List.Item>
          )}
        />
      )}
    </Card>
  );

  // 渲染最近活动
  const renderRecentActivities = () => (
    <Card title="最近活动" size="small">
      {recentActivities.length === 0 ? (
        <Text type="secondary">暂无最近活动</Text>
      ) : (
        <List
          size="small"
          dataSource={recentActivities}
          renderItem={(activity) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} size="small" />}
                title={activity.description}
                description={
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {new Date(activity.timestamp).toLocaleString()}
                  </Text>
                }
              />
            </List.Item>
          )}
        />
      )}
    </Card>
  );

  if (user?.role !== 'admin') {
    return (
      <Alert
        message="访问受限"
        description="您没有权限访问管理员仪表板"
        type="warning"
        showIcon
      />
    );
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={onCollapse}>
        <div className="logo" style={{ 
          height: '64px', 
          margin: '16px', 
          background: 'rgba(255, 255, 255, 0.2)', 
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          color: 'white',
          fontSize: collapsed ? '14px' : '18px',
          fontWeight: 'bold'
        }}>
          {collapsed ? 'WA' : 'WhatsApp管理'}
        </div>
        <Menu 
          theme="dark" 
          defaultSelectedKeys={[location.pathname]} 
          selectedKeys={[location.pathname]}
          mode="inline"
          onClick={handleMenuClick}
          items={menuItems}
        />
      </Sider>
      <Layout className="site-layout">
        <Header className="site-layout-background" style={{ padding: 0, background: '#fff' }}>
          <div style={{ float: 'right', marginRight: '20px' }}>
            <Button type="primary" danger icon={<LogoutOutlined />} onClick={handleLogout}>
              退出登录
            </Button>
          </div>
        </Header>
        <Content style={{ margin: '0 16px' }}>
          <Breadcrumb style={{ margin: '16px 0' }} items={breadcrumbItems} />
          <div className="site-layout-background" style={{ padding: 24, minHeight: 360, background: '#fff' }}>
            {isHome && <AdminHome />}
            <Outlet />
          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>WhatsApp中间平台 ©{new Date().getFullYear()} 管理员控制台</Footer>
      </Layout>
    </Layout>
  );
});

// 将AdminHome也包装为记忆化组件
const AdminHome = React.memo(() => {
  const [stats, setStats] = useState({
    userCount: 0,
    activeConnections: 0,
    todayMessages: 0,
    presetFileCount: 0,
    userActivity: {
      activeUsers: '0/0',
      avgDailyMessages: 0,
      avgResponseTime: 0
    },
    systemPerformance: {
      cpuUsage: 0,
      memoryUsage: '',
      diskUsage: 0
    },
    recentOperations: []
  });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    console.log('AdminHome组件挂载，开始获取数据');
    fetchDashboardData();
    
    return () => {
      console.log('AdminHome组件卸载');
    };
  }, []);

  const fetchDashboardData = async () => {
    setLoading(true);
    try {
      const response = await api.get('/reports/dashboard/stats');
      if (response.data) {
        setStats(response.data);
      }
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
      message.error('获取系统统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Title level={2}>管理中心</Title>
      <Spin spinning={loading}>
        <Row gutter={16}>
          <Col span={6}>
            <Card>
              <Statistic
                title="注册用户"
                value={stats.userCount}
                prefix={<UserOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="活跃连接"
                value={stats.activeConnections}
                prefix={<TeamOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="今日消息量"
                value={stats.todayMessages}
                prefix={<MessageOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="预设文件数"
                value={stats.presetFileCount}
                prefix={<FileOutlined />}
              />
            </Card>
          </Col>
        </Row>
        
        <Title level={3} style={{ marginTop: '32px' }}>系统状态</Title>
        <Row gutter={16}>
          <Col span={8}>
            <Card title="用户活跃度" style={{ marginBottom: '16px' }}>
              <p>活跃用户: {stats.userActivity.activeUsers}</p>
              <p>平均每日消息: {stats.userActivity.avgDailyMessages}</p>
              <p>平均响应时间: {stats.userActivity.avgResponseTime}分钟</p>
            </Card>
          </Col>
          <Col span={8}>
            <Card title="系统性能" style={{ marginBottom: '16px' }}>
              <p>CPU使用率: {stats.systemPerformance.cpuUsage}%</p>
              <p>内存使用: {stats.systemPerformance.memoryUsage}</p>
              <p>磁盘使用: {stats.systemPerformance.diskUsage}%</p>
            </Card>
          </Col>
          <Col span={8}>
            <Card title="近期操作" style={{ marginBottom: '16px' }}>
              {stats.recentOperations.length > 0 ? (
                stats.recentOperations.map((op, index) => (
                  <p key={index}>{op.type}: {op.time}</p>
                ))
              ) : (
                <p>暂无操作记录</p>
              )}
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
});

export default AdminDashboard; 